package com.itheima.web.adminmanager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminManager {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @DubboReference
    private AdminService adminService;
  //生成验证码
    public LineCaptcha verification(String uuid) {
        LineCaptcha lineCaptcha = new LineCaptcha(200, 100);
        //将验证码存入Redis中
        String ssm = lineCaptcha.getCode();
        redisTemplate.opsForValue().set(uuid,ssm, Duration.ofMinutes(5));
        return lineCaptcha;
    }
// 用户登录
    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //判断验证码是否正确
        String ssm = redisTemplate.opsForValue().get(uuid);
        if (!StrUtil.equals(ssm,verificationCode)) {
            throw new BusinessException("验证码错误！！");
        }
        //判断用户是否存在
        Admin admin = adminService.findByUserName(username);
        if (admin==null){
            throw new BusinessException("用户名不存在！");
        }
        password = SecureUtil.md5(password);
        if (!StrUtil.equals(password,admin.getPassword())) {
            throw new BusinessException("密码错误!");
        }
        // 5.登录成功
        // 5.1清除redis中验证码
        redisTemplate.delete(uuid);
        //通过验证，制作令牌
        admin.setPassword(null);
        Map<String, Object> map = BeanUtil.beanToMap(admin);
        String token = JwtUtil.createToken(map);
        //Map map2 = JwtUtil.parseToken(token);
        //System.err.println(map2);
        //将taken存入redis中
        String json = JSON.toJSONString(admin);
        redisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,json,Duration.ofHours(1));
        // 6.返回token
        Map<String, String> map1 = new HashMap<>();
        map1.put("token", token);
      return ResponseEntity.ok(map1);
    }
    //解析token
    public Admin findUserByToken(String token) {
        // 1.对token进行非空判断
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        //获得redis中的token
        token= token.replaceAll("Bearer ","");
        String lingpai = redisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        if (StrUtil.isEmpty(lingpai)) {
            return null;
        }
        Admin admin = JSON.parseObject(lingpai, Admin.class);
         redisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,lingpai,Duration.ofDays(7));
        return  admin;
    }
    //退出登录
    public void logout(String token) {
        // 1.处理token  注意：此处有空格
        token = token.replaceAll("Bearer ", "");
        //删除redis
        redisTemplate.delete(ConstantUtil.ADMIN_TOKEN+token);
    }
}
